package com.servlet;


import com.dao.LoginDao;
import com.dao.imp.LoginDaoImp;
import com.entity.User;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @author Mathison
 * @Title: LoginServlet
 * @Package: com.servlet
 * @Description: 登录验证
 * @date 2021/11/15 15:33
 **/

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        ServletContext application = session.getServletContext();
        Set<String> onlineUserSet;
        Map userStatusMap;
//        System.out.println(request.getAttribute(""));
        int userId = Integer.parseInt(request.getParameter("userId"));
        String password = (String) request.getParameter("password");
        //传入账号密码返回是否验证通过
//        if (){
//            拿到user写入session,map中status==0登陆成功
//        }else {
//            设置status==1,登陆失败
//        }
        LoginDao loginTest = new LoginDaoImp();

        if(loginTest.login(String.valueOf(userId),password)){
            //拿到登录的用户对象
            User user = (User) loginTest.loginResult(String.valueOf(userId),password);
            //添加session属性，标记当前session
            session.setAttribute("userId",user.getUser_id());
            //拿到application中存放的在线用户集与用户状态图；
            onlineUserSet = (Set)application.getAttribute("onlineUserSet");
            onlineUserSet.add(String.valueOf(user.getUser_id()));

            userStatusMap = (Map)application.getAttribute("userStatusMap");
            userStatusMap.put(user.getUser_id(),0);//状态0表示登陆成功
            userStatusMap.put(user.getUser_id()+"nickname",user);
//            System.out.println("userID"+userStatusMap.get(userId));
//            System.out.println("get:"+userStatusMap.get(user.getUser_id()));
        }else {
            userStatusMap = (Map)application.getAttribute("userStatusMap");
            userStatusMap.put(userId,1);
        }
//        System.out.println("userstatus:"+userStatusMap.get(userId));
        String jsonString = "{status:"+userStatusMap.get(userId)+"}";
//        System.out.println(jsonString);
        JSONObject json = JSONObject.fromObject(jsonString);

        response.getWriter().print(json);
    }
}
